package icu.feigroup.domain.trade.service.locak;

import icu.feigroup.domain.trade.adapter.repository.ITradeRepository;
import icu.feigroup.domain.trade.model.aggregate.GroupBuyOrderAggregate;
import icu.feigroup.domain.trade.model.entity.*;
import icu.feigroup.domain.trade.model.valobj.GroupBuyProgressVO;
import icu.feigroup.domain.trade.service.ITradeLockOrderService;
import icu.feigroup.domain.trade.service.locak.factory.TradeLockRuleFilterFactory;
import icu.feigroup.types.design.framwork.link.model2.chain.BusinessLinkedList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * projectName:icu.feigroup.domain.trade.service
 *
 * @author 飞
 * @since 2025/2/23 12:09
 * description:
 */
@Slf4j
@Service
public class TradeLockOrderServiceImpl implements ITradeLockOrderService {
    @Resource
    private ITradeRepository tradeRepository;

    @Resource
    private BusinessLinkedList<TradeLockRuleCommandEntity, TradeLockRuleFilterFactory.DynamicContext, TradeLockRuleFilterBackEntity> tradeRuleFilter;
    @Override
    public MarketPayOrderEntity queryNoPayMarketPayOrderByOutTradeNo(String userId, String outTradeNo) {
        log.info("拼团交易-查询未支付营销订单:{} outTradeNo:{}", userId, outTradeNo);
        return tradeRepository.queryPayMarketPayOrderByOutTradeNo(userId,outTradeNo);
    }

    @Override
    public GroupBuyProgressVO queryGroupBuyProgress(String teamId) {
        log.info("拼团交易-查询拼单进度:{}", teamId);
        return tradeRepository.queryGroupBuyProgress(teamId);
    }

    @Override
    public MarketPayOrderEntity lockMarketPayOrder(UserEntity userEntity, PayActivityEntity payActivityEntity, PayDiscountEntity payDiscountEntity) throws Exception {
        log.info("拼团交易-锁定营销优惠支付订单:{} activityId:{} goodsId:{}", userEntity.getUserId(), payActivityEntity.getActivityId(), payDiscountEntity.getGoodsId());
        TradeLockRuleFilterBackEntity tradeLockRuleFilterBackEntity = tradeRuleFilter.apply(TradeLockRuleCommandEntity.builder()
                .activityId(payActivityEntity.getActivityId())
                .userId(userEntity.getUserId())
                .build(), new TradeLockRuleFilterFactory.DynamicContext());

        Integer count = tradeLockRuleFilterBackEntity.getUserTakeOrderCount();

        GroupBuyOrderAggregate groupBuyOrderAggregate = GroupBuyOrderAggregate.builder()
                .userEntity(userEntity)
                .payActivityEntity(payActivityEntity)
                .payDiscountEntity(payDiscountEntity)
                .userTakeOrderCount(count)
                .build();
        return tradeRepository.lockMarketPayOrder(groupBuyOrderAggregate);
    }
}
